<?php

namespace app\api\controller\meiriyiwen;

use app\admin\model\Meiriyiwen;
use app\api\controller\Base;
use QL\QueryList;

/**
 * 文章接口
 */
class Articles extends Base
{

    public function get_today()
    {
        $today = date("Y-m-d",time());
        if (Meiriyiwen::get(['today' => $today])) {
            return;
        } else {
            $ql = QueryList::get('https://meiriyiwen.com/');
            $article = new Meiriyiwen();
            $article->today = $today;
            $article->title = $ql->find('h1')->text();
            $article->author = $ql->find('.article_author')->text();
            $article->content = $ql->find('.article_text')->html();
            $article->save();
        }
    }

    // 每日一文(当天/按id查询)
    public function today()
    {
        $id = $this->request->param('id');
        if ($id) {
            $article = Meiriyiwen::get($id);
        } else {
            $today = date("Y-m-d",time());
            $article = Meiriyiwen::get(['today' => $today]);

            if (!$article) {
                $ql = QueryList::get('https://meiriyiwen.com/');
                $article = new Meiriyiwen();
                $article->today = $today;
                $article->title = $ql->find('h1')->text();
                $article->author = $ql->find('.article_author')->text();
                $article->content = $ql->find('.article_text')->html();
                $article->save();
            }
        }

        $data['id'] = $article->id;
        $data['title'] = $article->title;
        $data['author'] = $article->author;
        $data['article'] = $article->content;

        $this->result('data', $data);
    }

    // 每日一文(随机)
    public function random()
    {
        $ql = QueryList::get('https://meiriyiwen.com/random');

        $article = new Meiriyiwen();
        $article->title = $ql->find('h1')->text();
        $article->author = $ql->find('.article_author')->text();
        $article->content = $ql->find('.article_text')->html();
        $article->save();

        $data['id'] = $article->id;
        $data['title'] = $article->title;
        $data['author'] = $article->author;
        $data['article'] = $article->content;

        $this->result('data', $data);
    }

}
